/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package file;

import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.swing.JOptionPane;

public class PrintToPrinter {

    private String arg;

    public PrintToPrinter(String arg) {
        this.arg = arg;

        createPdf();

    }

    
    private void createPdf() {

        try {
            Paragraph pg = new Paragraph(arg.replaceAll("null  ", ""));
            Font font = new Font(Font.COURIER, 10, Font.BOLD);
            pg.setFont(font);
            Document doc = new Document(new Rectangle(PageSize.A4), 20, 20, 20, 20);
            PdfWriter.getInstance(doc, new FileOutputStream("//tmp/file.000"));
            doc.open();
            doc.setMargins(0, 0, 5, 0);
            doc.add(pg);
            doc.close();
        } catch (Exception ex) {
            Logger.getLogger(PrintToPrinter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void printFile() {
        String filename = "//tmp/file.000";
        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
        DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;
        PrintService service = PrintServiceLookup.lookupDefaultPrintService();
        if (service != null) {
            try {
                DocPrintJob job = service.createPrintJob();
                FileInputStream fis = new FileInputStream(filename);
                DocAttributeSet das = new HashDocAttributeSet();
                Doc doc = new SimpleDoc(fis, flavor, das);
                JOptionPane.showMessageDialog(null, "Enviado para a impressora: \n" + service.getName());
                job.print(doc, pras);
                Thread.sleep(600);
                
            } catch (Exception ex) {
                Logger.getLogger(PrintToPrinter.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

}
}